﻿namespace WhenAllDemo
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            await ReadTextLis();

            int s = await GetTextCount();
            Console.WriteLine(s);
        }

        static async Task<int> GetTextCount()
        {
            string[] files = Directory.GetFiles(@"D:\test");
            Task<int>[] countTask = new Task<int>[files.Length];
            for (int i = 0; i < files.Length; i++)
            {
                string filename = files[i];
                Task<int> t = ReadTextCount(filename);
                countTask[i] = t;
            }
            int[] s = await Task.WhenAll(countTask);
            return s.Sum();
        }

        /// <summary>
        /// 获取文件的长度
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        static async Task<int> ReadTextCount(string filename)
        {
            string s = await File.ReadAllTextAsync(filename);
            return s.Length;
        }

        static async Task ReadTextLis()
        {
            Task<string> t1 = File.ReadAllTextAsync(@"d:\test\1.txt");
            Task<string> t2 = File.ReadAllTextAsync(@"d:\test\2.txt");
            Task<string> t3 = File.ReadAllTextAsync(@"d:\test\3.txt");

            string[] s = await Task.WhenAll(t1, t2, t3);
            string s1 = s[0];
            string s2 = s[1];
            string s3 = s[2];
            Console.WriteLine(s1);
            Console.WriteLine(s3);
            Console.WriteLine(s2);
        }

        static async IAsyncEnumerable<string> test()
        {
            yield return "1";
            yield return "2";
            yield return "3";
        }
    }
}